package com.idbk.chargestation.activity.user;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.idbk.chargestation.AppContext;
import com.idbk.chargestation.R;
import com.idbk.chargestation.api.APIForFile;
import com.idbk.chargestation.api.ChargeStationAPI;
import com.idbk.chargestation.api.ChargeStationURL;
import com.idbk.chargestation.app.ManagerCache;
import com.idbk.chargestation.base.BaseActivity;
import com.idbk.chargestation.bean.JsonBase;
import com.idbk.chargestation.bean.JsonUser;
import com.idbk.chargestation.net.EHttpResponse;
import com.idbk.chargestation.util.Const;
import com.idbk.chargestation.util.GlobalResult;
import com.idbk.chargestation.util.GsonUtils;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.request.RequestCall;

import java.io.File;

import okhttp3.Call;

/**
 * 用户信息展示界面
 *
 * @author lupc, zhx
 */
public class ActivityUserInfor extends BaseActivity implements OnClickListener {

    private final static String TAG = ActivityUserInfor.class.getSimpleName();

    private final static int CROP = 200;

    private final static String FILE_NAME_USER_HEADER_CAMERA = "user_header_camera.jpg";

    private final int REQUEST_CODE_CAMERA = 99;

    private Context context;

    private ProgressDialog dialog;

    private Uri origUri;

    private TextView tvName, tvSignature, tvAddress, tvCard, tvZip;
    private ImageView mImageHeader;
    private JsonUser result;

    private String mCropImageName,mUsermobile, userMobile;

    private TextView mTextLoginName, mTextPhone;

    private int mUserRole;

    private LinearLayout mLayoutError, mLinearBind, mLinearId;
    private ScrollView scrollView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_user_infor);

        context = this;

        setupView();

        setupData();
    }

    private void setupView() {
        if(AppContext.getInstance().getUserRole()==1){
            findViewById(R.id.layout_userbindphone).setVisibility(View.GONE);
        }
        mTextLoginName = (TextView) findViewById(R.id.textview_loginName);
        tvName = (TextView) findViewById(R.id.textview_userNickName);
        mLinearId = (LinearLayout) findViewById(R.id.layout_id) ;
        mLinearBind = (LinearLayout) findViewById(R.id.layout_userbindphone) ;
        mLinearBind.setVisibility(View.GONE);
        mLinearId.setVisibility(View.GONE);

        tvSignature = (TextView) findViewById(R.id.activity_userinfo_changesignature);
        mTextPhone = (TextView) findViewById(R.id.textview_userPhone);
        tvAddress = (TextView) findViewById(R.id.activity_userinfo_address);
        tvCard = (TextView) findViewById(R.id.activity_userinfo_card);
        tvZip = (TextView) findViewById(R.id.activity_userinfo_zip);
        mLayoutError = (LinearLayout) findViewById(R.id.tj_error_view);
        if (mLayoutError != null) {
            mLayoutError.setOnClickListener(this);
        }
        scrollView = (ScrollView) findViewById(R.id.scrollview_infor);
        mImageHeader = (ImageView) findViewById(R.id.imageview_header);
        initOnClickView();
    }

    @SuppressWarnings("ConstantConditions")
    private void initOnClickView() {
        findViewById(R.id.toolbar_back).setOnClickListener(this);
        findViewById(R.id.change_passwork).setOnClickListener(this);
        findViewById(R.id.textview_logout).setOnClickListener(this);
        findViewById(R.id.layout_headerImage).setOnClickListener(this);
        findViewById(R.id.layout_userNickName).setOnClickListener(this);
        findViewById(R.id.layout_userPhone).setOnClickListener(this);
        findViewById(R.id.layout_userAddress).setOnClickListener(this);
        findViewById(R.id.layout_userZip).setOnClickListener(this);
        findViewById(R.id.layout_userCardNo).setOnClickListener(this);
        findViewById(R.id.layout_userSignature).setOnClickListener(this);
        findViewById(R.id.layout_userbindphone).setOnClickListener(this);
    }

    private void setupData() {
        //显示加载框
        showMyProgressDialog(true, true, "载入中...");
        mMainRequest = ChargeStationAPI.getUserInfo(mResponse);
    }

    private final EHttpResponse mResponse = new EHttpResponse() {

        @Override
        public void onEResponse(String response) {
            result = GsonUtils.toBean(JsonUser.class, response);//解析结果
            if (result == null) {
                Toast.makeText(getApplicationContext(), R.string.common_tip_rusultzero, Toast.LENGTH_SHORT).show();
            } else if (result.status == GlobalResult.OK.getStatus()) {
                //绑定数据
                mLayoutError.setVisibility(View.GONE);
                scrollView.setVisibility(View.VISIBLE);
                bindView(result);
                mUsermobile = result.mobile;
            } else {
                Toast.makeText(getApplicationContext(), result.message, Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onEErrorResponse(VolleyError error) {
            //打印调试信息
            Log.e(TAG, error.getMessage(), error.getCause());
            mLayoutError.setVisibility(View.VISIBLE);
            scrollView.setVisibility(View.GONE);
        }

        @Override
        public void onEFinish() {
            //关闭 等待框
            super.onEFinish();
            dismissMyProgressDialog();
        }

    };


    private void bindView(JsonUser result) {
        String mMobile, mMobileSub;
        mTextLoginName.setText(result.loginUser);
        tvName.setText(result.realName);
        tvAddress.setText(result.address);
        tvCard.setText(result.cardNo);
        tvZip.setText(result.zip);
        if (result.mobile != null) {
            if (result.mobile.length() == 11) {
                mMobile = result.mobile;
                mMobileSub = mMobile.substring(0, 3) + "****" + mMobile.substring(7, mMobile.length());
                mTextPhone.setText(mMobileSub);
            } else {
                mTextPhone.setText(result.mobile);
            }
        }

        //个性签名这个字段暂时不支持
        if (result.signature == null || result.signature.equals("") || result.signature.length() < 1)
            tvSignature.setText("我很懒，什么都没写");
        else
            tvSignature.setText(result.signature);

        //用户头像
        String url = ChargeStationURL.getRootURL() + result.imageURL;
        Picasso.with(this)
                .load(url)
                .error(R.drawable.header_default)
                .into(mImageHeader);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tj_error_view:
                setupData();
                break;
            case R.id.textview_logout:
                logout();
                break;
            case R.id.layout_headerImage:
                uploadImage();
                break;
            case R.id.toolbar_back:
                finish();
                break;
            case R.id.change_passwork:
                changePassword();
                break;
            case R.id.layout_userbindphone:
                bindPhone();
                break;
            case R.id.layout_userNickName:
                jumpToActivityUserInforSet(ActivityUserInforSet.INDEX_USER_NICK_NAME);
                break;
            case R.id.layout_userPhone:
                if (AppContext.getInstance().getUserRole() == JsonUser.COMMON_USER) {
                    jumpToActivityUserInforSet(ActivityUserInforSet.INDEX_USER_PHONE);
                }
                break;
            case R.id.layout_userAddress:
                jumpToActivityUserInforSet(ActivityUserInforSet.INDEX_USER_ADDRESS);
                break;
            case R.id.layout_userZip:
                jumpToActivityUserInforSet(ActivityUserInforSet.INDEX_USER_ZIP);
                break;
            case R.id.layout_userCardNo:
                jumpToActivityUserInforSet(ActivityUserInforSet.INDEX_USER_CARD);
                break;
            case R.id.layout_userSignature:
                jumpToActivityUserInforSet(ActivityUserInforSet.INDEX_USER_SIGNATURE);
                break;
            default:
                break;
        }
    }

    private void bindPhone(){
        mUserRole = AppContext.getInstance().getUserRole();
        Log.e(TAG,"mUsermobile=  "+ mUsermobile);
        if (mUserRole ==  JsonUser.ENTERPRISE_NUMBER_USER && ( mUsermobile == null || mUsermobile.equals(""))){
            Intent intent = new Intent(ActivityUserInfor.this,ActivityBindPhone.class);
            startActivityForResult(intent, Const.CODE_REQUEST_EDIT);
        }
        if (mUserRole ==  JsonUser.ENTERPRISE_NUMBER_USER && mUsermobile != null && !mUsermobile.equals("")){
            Intent intent  = new Intent(ActivityUserInfor.this,ActivityUnbindPhone.class);
            startActivityForResult(intent, Const.CODE_REQUEST_EDIT);
        }
    }

    private void changePassword(){
        mUserRole = AppContext.getInstance().getUserRole();
        if ( mUserRole == 2 && (mUsermobile == null || mUsermobile.equals("")) ) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(ActivityUserInfor.this);
            dialog.setMessage("修改密码需要绑定手机号，是否前往？");
            dialog.setCancelable(true);
            dialog.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(ActivityUserInfor.this,ActivityBindPhone.class);
                    startActivityForResult(intent, Const.CODE_REQUEST_EDIT);
                }
            });
            dialog.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
        else{
            Intent intent = new Intent(context, ActivityResetPassword.class);
            intent.putExtra("userMobile", result.mobile);
            startActivity(intent);
        }
    }

    private void jumpToActivityUserInforSet(int userFlag) {
        Intent intent = new Intent(context, ActivityUserInforSet.class);
        intent.putExtra(JsonUser.KEY, result);
        intent.putExtra(ActivityUserInforSet.KEY_EDIT_INDEX, userFlag);
        startActivityForResult(intent, Const.CODE_REQUEST_EDIT);
    }

    private void logout() {
        ChargeStationAPI.logout(new EHttpResponse() {

            @Override
            public void onEResponse(String response) {
                Toast.makeText(getApplicationContext(), R.string.activity_userinfo_logout_success, Toast.LENGTH_SHORT).show();
            }
        });
        AppContext.getInstance().logout();
        finish();
    }

    private void uploadImage() {
        if (!ManagerCache.isSDCARDMounted()) {
            Snackbar.make(mImageHeader, "错误，无法找到SD卡！", Snackbar.LENGTH_LONG).show();
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCancelable(true)
                .setItems(new String[]{"相册", "相机"}, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            startImagePick();
                        } else {
                            checkAndStartTakePhoto();
                        }
                        dialog.dismiss();
                    }
                })
                .show();
    }

    //从相册选取
    private void startImagePick() {
        Intent intent;
        if (Build.VERSION.SDK_INT < 19) {
            intent = new Intent();
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.setType("image/*");
            startActivityForResult(
                    Intent.createChooser(intent, "选择图片"),
                    Const.CODE_REQUEST_GETIMAGE_BYCROP);
        } else {
            intent = new Intent(Intent.ACTION_PICK,
                    Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(Intent.createChooser(intent, "选择图片"),
                    Const.CODE_REQUEST_GETIMAGE_BYCROP);
        }
    }

    //从相机选取
    private void checkAndStartTakePhoto() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    this,
                    new String[]{Manifest.permission.CAMERA},
                    REQUEST_CODE_CAMERA);
        } else {
            startTakePhoto();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @Nullable String[] permissions, @Nullable int[] grantResults) {
        if (permissions != null && grantResults != null) {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (requestCode == REQUEST_CODE_CAMERA) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    startTakePhoto();
                } else {
                    showMissingPermissionDialog();
                }
            }
        }
    }

    private void startTakePhoto() {
        File file = new File(getExternalFilesDir(null), FILE_NAME_USER_HEADER_CAMERA);
        Uri uri = Uri.fromFile(file);
        origUri = uri;

        Log.d(TAG, "照片绝对路径：" + file.getPath());//该照片的绝对路径

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, Const.CODE_REQUEST_GETIMAGE_BYCAMARA);
    }

    //裁剪头像的绝对路径
    private Uri getUploadTempFile(Uri uri) {
        //根据uri获取文件路径
        String thePath = getAbsolutePathFromNoStandardUri(uri);
        //如果是标准uri
        if (thePath == null || thePath.equals("") || thePath.length() < 1) {
            thePath = getAbsoluteImagePath(this, uri);
        }
        String ext = thePath.substring(thePath.lastIndexOf(".") + 1);
        if (ext.equals("") || ext.equals("") || ext.length() < 1)
            ext = "jpg";

        //照片命名
        mCropImageName = "user_header_croped." + ext;
        //裁剪头像的绝对路径
        File file = new File(getExternalFilesDir(null), mCropImageName);

        return Uri.fromFile(file);
    }

    private static String getAbsolutePathFromNoStandardUri(Uri mUri) {
        String filePath = null;

        String mUriString = mUri.toString();
        mUriString = Uri.decode(mUriString);

        String pre1 = "file://" + "/sdcard" + File.separator;
        String pre2 = "file://" + "/mnt/sdcard" + File.separator;

        if (mUriString.startsWith(pre1)) {
            filePath = Environment.getExternalStorageDirectory().getPath()
                    + File.separator + mUriString.substring(pre1.length());
        } else if (mUriString.startsWith(pre2)) {
            filePath = Environment.getExternalStorageDirectory().getPath()
                    + File.separator + mUriString.substring(pre2.length());
        }
        return filePath;
    }

    private static String getAbsoluteImagePath(Activity context, Uri uri) {
        String imagePath = "";
        String[] proj = {Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);

        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(Images.Media.DATA);
            if (cursor.getCount() > 0 && cursor.moveToFirst()) {
                imagePath = cursor.getString(columnIndex);
            }
            cursor.close();
        }
        return imagePath;
    }

    //开始裁剪图片
    private void startActionCrop(Uri data) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(data, "image/*");
        intent.putExtra("output", getUploadTempFile(data));
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);//
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", CROP);
        intent.putExtra("outputY", CROP);
        intent.putExtra("scale", true);
        intent.putExtra("scaleUpIfNeeded", true);
        startActivityForResult(intent, Const.CODE_REQUEST_GETIMAGE_BYSDCARD);
    }

    private RequestCall mRequest;

    //上传图片到服务器
    private void updateNewPhoto() {
        //
        if (mCropImageName == null) {
            Snackbar.make(mImageHeader, "错误，无法找到剪切图！", Snackbar.LENGTH_LONG).show();
        }
        final File file = new File(getExternalFilesDir(null), mCropImageName);
        if (!file.exists()) {
            Snackbar.make(mImageHeader, "错误，无法找到剪切图！", Snackbar.LENGTH_LONG).show();
        }

        //正在上传头像...
        dialog = ProgressDialog.show(context, null, "正在上传头像...", true, true, new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                if (mRequest != null) {
                    mRequest.cancel();
                }
            }
        });

        mRequest = APIForFile.uploadHeaderImage(file, new StringCallback() {

            @Override
            public void onResponse(String response, int id) {
                dialog.dismiss();
                JsonBase result = GsonUtils.toBean(JsonBase.class, response);//解析结果
                if (result != null && result.status == GlobalResult.OK.getStatus()) {
                    //更新头像
                    mImageHeader.setImageBitmap(BitmapFactory.decodeFile(file.getPath()));
                    Toast.makeText(context, "更换头像成功", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "更换头像失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                dialog.dismiss();
                Toast.makeText(context, "更换头像失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //编辑相关
        if (requestCode == Const.CODE_REQUEST_EDIT && resultCode == Activity.RESULT_OK) {
            //重新获取数据
            setupData();
            return;
        }
        //头像相关
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == Const.CODE_REQUEST_GETIMAGE_BYCROP) {
                startActionCrop(data.getData());//选图后裁剪
            } else if (requestCode == Const.CODE_REQUEST_GETIMAGE_BYCAMARA) {
                startActionCrop(origUri);//拍照后裁剪
            } else if (requestCode == Const.CODE_REQUEST_GETIMAGE_BYSDCARD) {
                updateNewPhoto();//从sd卡中选取处理后的图片进行上传
            }
        }
    }

}
